package mwt.xml.xdbforms.schemalayer.types;

import javax.xml.XMLConstants;
import mwt.xml.xdbforms.dblayer.metadata.impl.ColumnMetaData;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;


public class XmlEnum extends XmlTypes {

    public XmlEnum() {
    }

    public XmlEnum(Document doc) {
        super(doc);
    }

    private void buildFragment(ColumnMetaData cmd) {

        Element xtype, restriction;
        Element enumeration;

        fragment = doc.createDocumentFragment();
        xtype = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI,"xs:simpleType");
        cmd.setXschemaTypeName(typeName);
      
        xtype.setAttribute("name", typeName);

        restriction = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI,"xs:restriction");

        // Tutti le enumerazioni sono di tipo stringa o char
        restriction.setAttribute("base", "xs:string");
        String[] values = cmd.getEnumSetValues();

        for (int i = 0; i < values.length; i++) {
            String value = values[i];
            enumeration = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI,"xs:enumeration");
            enumeration.setAttribute("value", value);
            restriction.appendChild(enumeration);
        }

        xtype.appendChild(restriction);
        fragment.appendChild(xtype);

    }

    @Override
    public DocumentFragment getSchemaType(ColumnMetaData cmd) {

        typeName = cmd.getTypeName();

        if (typeName.equals("ENUM")) {

            buildFragment(cmd);
            return fragment;
        } else {

            return nextType.getSchemaType(cmd);

        }


    }

    @Override
    public Object getXSchemaToJavaType(String baseType, String value) {
        if(baseType.startsWith("ENUM")){

            return value;
        }else{

            return nextType.getXSchemaToJavaType(baseType, value);
        }

    }
}

